package com.neeraj.SharingArtifacts;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.Dialog;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class DownloadArtifact extends Activity {
	
	private static final String IP_ADDRESS = "192.168.1.67";
//	private static final String IP_ADDRESS = "pba.cs.clemson.edu/~neerajj";
	private static final String DEBUG_TAG = "DOWNLOAD ARTIFACT";
	
    private ImageView imgView;
    private VideoView videoView;
    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    TextView cur_val;
    String dwnload_file_path;   
    String filename;
    File downloadDir;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle b = this.getIntent().getExtras();
    	filename = b.getString("file");
    	if(!filename.equalsIgnoreCase("NO Artifacts found") && !filename.contains("TXT")) {
	    	dwnload_file_path = "http://"+ IP_ADDRESS+"/uploads/"+filename;
	        showProgress(dwnload_file_path);
	        new Thread(new Runnable() {
	        	public void run() {
	        		downloadFile();
	        	}
	        }).start();	        
    	}
    };
  	    
    void downloadFile(){
    	
    	try {
    		URL url = new URL(dwnload_file_path);
    		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);

    		//connect
    		urlConnection.connect();

    		//set the path where we want to save the file    		
    		downloadDir = new File(Environment.getExternalStoragePublicDirectory(
  	              Environment.DIRECTORY_DCIM), "SA.Downloads");

	  	    // Create the storage directory if it does not exist
	  	    if (! downloadDir.exists()){
	  	        if (! downloadDir.mkdirs()){
	  	            Log.d(DEBUG_TAG, "failed to create directory");  	            
	  	        }
	  	    }    	
    		//create a new file, to save the download file 
    		File file = new File(downloadDir,filename);
 
    		FileOutputStream fileOutput = new FileOutputStream(file);

    		//Stream used for reading the data from the internet
    		InputStream inputStream = urlConnection.getInputStream();

    		//this is the total size of the file which we are downloading
    		totalSize = urlConnection.getContentLength();

    		runOnUiThread(new Runnable() {
			    public void run() {
			    	pb.setMax(totalSize);
			    }			    
			});
    		
    		//create a buffer...
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;

    		while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    			fileOutput.write(buffer, 0, bufferLength);
    			downloadedSize += bufferLength;
    			// update the progressbar //
    			runOnUiThread(new Runnable() {
    			    public void run() {
    			    	pb.setProgress(downloadedSize);
    			    	float per = ((float)downloadedSize/totalSize) * 100;
    			    	cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
    			    }
    			});
    		}
    		//close the output stream when complete //
    		fileOutput.close();
    		runOnUiThread(new Runnable() {
			    public void run() {
//			    	pb.dismiss(); // if you want close it..
			    	dialog.dismiss();
			    	displayArtifact();
			    }
			});    		
    		
    	} catch (final MalformedURLException e) {
    		showError("Error : MalformedURLException " + e);  		
    		e.printStackTrace();
    	} catch (final IOException e) {
    		showError("Error : IOException " + e);  		
    		e.printStackTrace();
    	}
    	catch (final Exception e) {
    		showError("Error : Please check your internet connection " + e);
    	}    	
    }
    
    void showError(final String err){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	Toast.makeText(DownloadArtifact.this, err, Toast.LENGTH_LONG).show();
		    }
		});
    }
    
    void showProgress(String file_path){
    	dialog = new Dialog(this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.progress_dialog);
//    	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    	dialog.setTitle("Download Progress");

    	TextView text = (TextView) dialog.findViewById(R.id.tv1);
    	text.setText("Downloading file from ... " + file_path);
    	cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    	cur_val.setText("Starting download...");
    	dialog.show();
    	
    	pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    	pb.setProgress(0);
    	pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));  
    }
    
    void displayArtifact() {
    		try {    			
    			Log.i(DEBUG_TAG, ""+downloadDir);
    			Log.i(DEBUG_TAG, filename);
    			if(filename.contains("IMG")) {
    				Log.i(DEBUG_TAG, "Its a Image");
    				setContentView(R.layout.image_viewer);
//    				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    				imgView = (ImageView) findViewById(R.id.imageView);
    				Bitmap bm = BitmapFactory.decodeFile(downloadDir+"/"+filename);        			        			
        			imgView.setImageBitmap(bm);
    			}
    			else if(filename.contains("VID")) {
    				Log.i(DEBUG_TAG, "Its a Video");
    				setContentView(R.layout.video_viewer);
//    				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//    				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    				videoView = (VideoView)findViewById(R.id.videoView);
    			    videoView.setVideoURI(Uri.parse(downloadDir+"/"+filename));
    			    videoView.setMediaController(new MediaController(this));
    			    videoView.requestFocus();
    			    videoView.start();
    			}
    			else if(filename.contains("AUD")) {
    				Log.i(DEBUG_TAG, "Its a Audio");
    				setContentView(R.layout.video_viewer);
//    				setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
    				videoView = (VideoView)findViewById(R.id.videoView);
    			    videoView.setVideoURI(Uri.parse(downloadDir+"/"+filename));
    			    videoView.setMediaController(new MediaController(this));
    			    videoView.requestFocus();
    			    videoView.start();
    			}
    			    			
    			
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
//    	}    	
    }
}